import request from "./request";
import { API_URL } from "../constants";
import type {
  IDevice,
  IDeviceConstant,
  IDeviceProgram,
  IRequestListParams,
  IResponse,
  IResponseList,
} from "../types";

export function getDeviceList(
  params: IRequestListParams,
  token: string,
  signal?: AbortSignal,
) {
  return request<IResponseList & { rows: IDevice[] }>(
    `${API_URL}/business/device/list`,
    {
      params: params as Record<string, string>,
      headers: { Authorization: token },
      signal,
    },
  );
}

export function uploadDeviceImage(file: File, token: string) {
  const data = new FormData();
  data.append("file", file);
  return request<IResponse<{ fileName: string }>>(
    `${API_URL}/business/device/upload`,
    {
      method: "post",
      data,
      headers: { Authorization: token },
    },
  );
}

export function createDevice(data: Partial<IDevice>, token: string) {
  return request<IResponse>(`${API_URL}/business/device`, {
    method: "post",
    data,
    headers: { Authorization: token },
  });
}

export function updateDevice(data: Partial<IDevice>, token: string) {
  return request<IResponse>(`${API_URL}/business/device`, {
    method: "put",
    data,
    headers: { Authorization: token },
  });
}

export function deleteDevice(id: number, token: string) {
  return request<IResponse>(`${API_URL}/business/device/${id}`, {
    method: "delete",
    headers: { Authorization: token },
  });
}

export function getDeviceDetail(id: number, token: string) {
  return request<IResponse<{ data: IDevice }>>(
    `${API_URL}/business/device/${id}`,
    {
      headers: { Authorization: token },
    },
  );
}

export function getDeviceConstant(id: number, token: string) {
  return request<IResponse<{ data: IDeviceConstant }>>(
    `${API_URL}/business/deviceFix/${id}`,
    {
      headers: { Authorization: token },
    },
  );
}

export function updateDeviceConstant(
  data: Partial<IDeviceConstant>,
  token: string,
) {
  return request<IResponse>(`${API_URL}/business/deviceFix`, {
    method: "put",
    data,
    headers: { Authorization: token },
  });
}

export function getDeviceProgram(id: number, token: string) {
  return request<IResponse<{ data: IDeviceProgram }>>(
    `${API_URL}/business/deviceProgram/${id}`,
    {
      headers: { Authorization: token },
    },
  );
}

export function updateDeviceProgram(
  data: Partial<IDeviceProgram>,
  token: string,
) {
  return request<IResponse>(`${API_URL}/business/deviceProgram`, {
    method: "put",
    data,
    headers: { Authorization: token },
  });
}
